package com.nai365.nart.blockchain.listener;

import com.nai365.nart.blockchain.config.RabbitmqConfig;
import com.nai365.nart.blockchain.dto.TransferDto;
import com.nai365.nart.blockchain.dto.TransferResultDto;
import com.nai365.nart.blockchain.entity.DdcTransferRequest;
import com.nai365.nart.blockchain.mapper.AccountMapper;
import com.nai365.nart.blockchain.service.DDCService;
import com.rabbitmq.client.Channel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * DDC Listener
 *
 * @author linco
 * @date 2020-07-24
 * @since 1.0
 * @since 1.0
 */
@Component
@AllArgsConstructor
@Slf4j
public class DdcListener {

	private final DDCService ddcService;

	private final RabbitTemplate rabbitTemplate;


	@RabbitListener(queues = {RabbitmqConfig.TRANSFER_QUEUE})
	public void receiveTransfer(TransferDto transferDto, Message message, Channel channel) throws IOException {
		DdcTransferRequest request = null;
		try {
			request = ddcService.generateTransferRequest(transferDto);
			request = ddcService.transferByRequest(request);
			if (request.getIsSuccess()) {
				TransferResultDto result = new TransferResultDto();
				BeanUtils.copyProperties(transferDto, result);
				result.setTxId(result.getTxId());
				result.setTxHash(request.getTxHash());
				rabbitTemplate.convertAndSend(transferDto.getExchangeName(), transferDto.getNotifyRoute(), result);
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
			} else if (request.getRetries() <= 3) {
				channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
			}
		} catch (Exception e) {
			if (request == null || request.getRetries() <= 3) {
				channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
			}
		}
	}


}
